import web

count = 0

# init is called to initialize the server
# update is called to update the position of the joystick
urls = (
    '/init', 'init',
    '/update', 'update',
    '/stop', 'stop',
)

class init:
    def POST(self):
        global count
        count = 0
	ret = '<?xml version="1.0"?><Value>' + str(count) + '</Value>'
	web.header('Content-Type', 'text/xml')
	web.header('Access-Control-Allow-Origin', '*')
	return ret

class stop:
    def POST(self):
	ret = '<?xml version="1.0"?><Msg>OK</Msg>'
	web.header('Content-Type', 'text/xml')
	web.header('Access-Control-Allow-Origin', '*')
	return ret
        
class update:
    def parse_data(data):
	# internally think of each left and right going from -255 to +255
	# leftmost = 9, rightmost = 177, center about 94
	# cursor at top means left and right added = max (255?)
	# cursor at mid means left + right = 0
	# cursor at bottom means left + right = -255
	# cursor at left means left = right - max
	# cursor at center means left = right
	# cursor at right means left = right + max
	# so I don't go nuts, normalize left/right values from -1 to 1, and
	# same for top/bottom values
	left_float = (data.left - 9.0)/168.0 * 2.0 - 1.0
	top_float = (data.top - 9.0)/168.0 * 2.0 - 1.0
	# top float is now an absolute percentage of max that the two channels
	# combined should be
	# left_speed + right_speed = top
	# left_speed = right_speed + left
	# 2 * right_speed = top - left
	# right_speed = (top - left)/2
	# left_speed + (top - left)/2 = top
	# left_speed = top/2 + left/2
	

    def POST(self):
	data = web.data()
	web.debug(data)
	# transform the data into a dictionary telling us what to do
	# 'dir' -> 0 for backward, 1 for forwards
	# 'PWM' -> 0-255 value for speed of movement
	# each one is an array with two channels, 0 for left, 1 for right.
	dir, PWM = parse_data(data)
	web.debug(dir)
	web.debug(PWM)

        global count
        count = count + 1
	ret = '<?xml version="1.0"?><Value>' + str(count) + '</Value>'
	web.header('Content-Type', 'text/xml')
	web.header('Access-Control-Allow-Origin', '*')
	return ret

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

